package com.qfedu.ms.interceptor;

import com.qfedu.ms.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录过
        final HttpSession session = request.getSession();
        final Object o = session.getAttribute(Constants.USER_LOGIN_SESSION_KEY);
        log.info("从session中获取登录信息：{}",o);
        if(o != null){
            //登陆过了直接放行
            log.info("拦截到路径为：{},放行",request.getRequestURI());
            return true;
        }
        //如果没有登录，则重定向到登录页面
        response.sendRedirect("/login.html");
        log.info("拦截到的路径为：{}，重定向到登录页面！",request.getRequestURI());
        return false;
    }
}
